package gwtappcontainer.server.apis.insight;

import static com.googlecode.objectify.ObjectifyService.ofy;
import gwtappcontainer.server.DatastoreNamespaces;
import gwtappcontainer.server.apis.APIException;
import gwtappcontainer.shared.apis.APIResponse.Status;
import gwtappcontainer.shared.apis.insight.CenterProp;

import java.util.ArrayList;
import java.util.List;

import com.google.appengine.api.NamespaceManager;
import com.googlecode.objectify.ObjectifyService;

class CenterRepository {
	static {		
		ObjectifyService.factory().register(CenterEntity.class);		
	}	
	
	private final String NAMESPACE = DatastoreNamespaces.INSIGHT;
	
	List<CenterProp> list() {
		NamespaceManager.set(NAMESPACE);
		
		List<CenterEntity> entities = ofy().load().type(CenterEntity.class).list();
		
		List<CenterProp> props = new ArrayList<CenterProp>();
		
		for (CenterEntity entity : entities) {
			props.add(entity.toProp());
		}
		
		return props;
	}
	
	CenterProp add(String name) {
		NamespaceManager.set(NAMESPACE);
		List<CenterProp> all = list();
		
		//throw exception if already found
		for (CenterProp prop : all) {
			if (prop.name.equalsIgnoreCase(name))
				throw new APIException(Status.ERROR_RESOURCE_ALREADY_EXISTS, 
						"Center [" + name + "] already exists with id [" + prop.id + "]");
		}
		
		CenterEntity entity = new CenterEntity();
		entity.name = name;
		ofy().save().entity(entity).now();
		
		return entity.toProp();		
	}
	
	CenterProp update(String newName, String existingName) {
							
		NamespaceManager.set(NAMESPACE);
		List<CenterEntity> all = ofy().load().type(CenterEntity.class).list();
		
		//throw exception if existing name does not already exist
		CenterEntity entity = null;
		for (CenterEntity e : all) {
			if (e.name.equalsIgnoreCase(existingName))
				entity = e;
		}
		
		if (entity == null)
			throw new APIException(Status.ERROR_RESOURCE_DOES_NOT_EXIST, 
					"No center found with name [" + existingName + "]");
		
		entity.name = newName;
		ofy().save().entity(entity).now();
		
		return entity.toProp();
	}
}
